<template lang="pug">
  Modal(v-model="createModal" title="新增企业信息" :closable="!hasCustomerId" :mask-closable="!hasCustomerId" width="800")
    template(v-if="createModal")
      Steps(:current="createCurrent")
        Step(title="基本信息" icon="ios-person")
        Step(title="上传企业logo" icon="ios-card")
      Divider
      //- 基本信息
      div(v-show="createCurrent === 0")
        .form-shebao-title.font-16.font-weight 基本信息
        Form(ref="formValidate_t1" :model="formValidate_t1" :rules="ruleValidate_1" :label-width="150")
          FormItem(label="企业名称：" prop="name")
            Input(v-model="formValidate_t1.name" placeholder="请输入")
          FormItem(label="企业编码：")
            Input(v-model="formValidate_t1.code" placeholder="请输入")
          FormItem(label="上级公司名称：")
            Select(v-model="formValidate_t1.superCompanyId" filterable :label-in-value="true" placeholder="请选择" clearable @on-change="superCompanyIdChange")
              Option(v-for="(item, index) in superCompanyId_arr" :value="item.id" :key="index") {{ item.name }}
          Row(type="flex" justify="start")
            Col(span="12")
              FormItem(label="合作状态：")
                Select(v-model="formValidate_t1.status"  placeholder="请选择")
                  Option(v-for="(item, index) in cooperateStatuseType_arr" :value="item.key" :key="index") {{ item.value }}
            Col(span="12")
              FormItem(label="合作类型：" prop="type")
                Select.lzw-style(v-model="formValidate_t1.type" placeholder="请选择" clearable disabled)
                  Option(v-for="(item, index) in cooperateType_arr" :value="item.key" :key="index") {{ item.value }}
          FormItem(label="人事负责人姓名：" prop="hrContactName")
            Input(v-model="formValidate_t1.hrContactName" placeholder="请输入" clearable)
          FormItem(label="人事负责人电话：" prop="hrContactPhone")
            Input(v-model="formValidate_t1.hrContactPhone" placeholder="请输入" clearable)
          FormItem(label="客户所在城市：" prop="costomerCity_arr")
            Cascader(v-model="formValidate_t1.costomerCity_arr" placeholder="请选择" :filterable="true" :data="areaArr" :change-on-select="true" :load-data="loadDataCity" style="width:100%;" @on-change="costomerCityChange")

      //- 营业执照信息
      div(v-show="createCurrent === 1")
        .form-shebao-title.font-16.font-weight 企业附件信息
        Form(ref="formValidate_t2" :label-width="150")
          FormItem(label="企业logo：")
            .d-flex
              .position-relative.mr-10
                img(v-if="logo_img" :src="imgUrl" @click="previewImg")
                Icon.img-close(v-if="logo_img" type="md-close-circle" size="20" @click="deleteImg")
                Upload.mb-20(v-show="!logo_img" ref="licenseUploadRef" :before-upload="licenseUpload" :action="uploadBaseUrl+'/Customer/'+createCustomerId+'/Upload'" :data="{categoryname: '企业logo'}" :format="['jpg','jpeg','png']")
                  .license-img
                    Icon( type="ios-image-outline" size="60")
              span 支持jpg、jpeg、png格式
          //- FormItem(label="营业执照：")
          //-   .d-flex
          //-     .position-relative.mr-10
          //-       img(v-if="logo_img" :src="imgUrl" @click="previewImg")
          //-       Icon.img-close(v-if="logo_img" type="md-close-circle" size="20" @click="deleteImg")
          //-       Upload.mb-20(v-show="!logo_img" ref="licenseUploadRef" :before-upload="licenseUpload" :action="uploadBaseUrl+'/Customer/'+createCustomerId+'/Upload'" :data="{categoryname: '企业logo'}" :format="['jpg','jpeg','png']")
          //-         .license-img
          //-           Icon( type="ios-image-outline" size="60")
          //-     span 支持jpg、jpeg、png格式

    template(slot="footer")
      Button(type="info" v-if="createCurrent === 0" @click="stepSubmit_1('formValidate_t1')") 保存并跳转下一步
      Button(type="info" v-if="createCurrent === 1" @click="stepSubmit_2") 完成并关闭

</template>

<script>
import dataApi from '@/api/data'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  props: {
    areaArr: Array,
    superCompanyId_arr: Array
  },
  data () {
    return {
      createCustomerId: '', // 新创建企业的id
      hasCustomerId: false, // 是否已经获得企业id
      createModal: false,
      createCurrent: 0,
      uploadBaseUrl: baseUrl, //
      // 基本信息
      formValidate_t1: {
        costomerCity_arr: [],
        id: '', // 客户ID,新增为空
        name: '', // 客户名称
        code: '', // 客户编码
        superCompanyId: '', // 上级公司ID
        superCompanyName: '', // 上级公司名称
        status: '1', // 合作状态
        type: '4', // 合作类型
        category: '', // 客户分类ID
        categoryName: '', // 客户分类名称
        character: '', // 公司性质
        characterName: '', // 公司性质名称
        hrContactName: '', // 人事负责人姓名
        hrContactPhone: '', // 人事负责人电话
        hrContactEmail: '', // 人事负责人邮箱
        inChargeContacName: '', // 关键决策人姓名
        inChargeContacPhone: '', // 关键决策人电话
        inChargeContacTitle: '', // 关键决策人职务
        phone: '', // 电话
        email: '', // 邮箱
        webSite: '', // 网站
        postCode: '', // 邮编
        cityId: '', // 客户所在城市ID
        cityName: '', // 客户所在城市名称
        AreaPath: '',
        serverId: '00000000-0000-0000-0000-000000000000',
        serverName: '',
        address: '', // 地址
        description: '', // 描述
        rowversion: '', // 新为空,修改时原值返回
        DataSource: '1'
      },
      logo_img: '', // 企业logo
      imgUrl: '',
      // 验证规则
      ruleValidate_1: {
        costomerCity_arr: [
          { required: true, type: 'array', min: 1, message: '请选择地址', trigger: 'change' }
        ],
        name: [
          { required: true, message: '客户姓名不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '编码不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '合作类型不能为空', trigger: 'change' }
        ],
        hrContactName: [
          { required: true, message: '人事负责人姓名不能为空', trigger: 'blur' }
        ],
        hrContactPhone: [
          { required: true, message: '人事负责人电话不能为空', trigger: 'blur' }
          // {type: "string", message: '电话格式不正确', pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, trigger: 'blur'}
        ]
      }
    }
  },
  created () {
    this.getEnum()
  },
  watch: {
    createModal () {
      this.getEnum()
    }
  },
  methods: {
    creatOpen () {
      this.createModal = true
      this.hasCustomerId = false
    },
    loadDataCity (val, callback) {
      val.loading = true
      if (val.levelID === 2) {
        dataApi.getCity({ parentId: val.value }).then(res => {
          val.children = res.data.data.map(item => {
            return {
              ...item,
              label: item.name,
              value: item.id,
              children: []
              // loading: false
            }
          })
          val.loading = false
          callback()
        })
      } else {
        // dataApi.getArea({parentId: val.value}).then(res => {
        //   val.children = res.data.data.map(item => {
        //     return {...item, label: item.name, value: item.id}
        //   })
        //   val.loading = false
        //   callback()
        // })
      }
    },

    // 客户所在城市选择
    costomerCityChange (value, selectedData) {
      console.log(value, selectedData)
      this.formValidate_t1.AreaPath = value.join(',')
      console.log(this.formValidate_t1.AreaPath)
      if (value.length > 0) {
        this.formValidate_t1.cityId = value[value.length - 1]
        this.formValidate_t1.cityName = selectedData[selectedData.length - 1].name
      } else {
        this.formValidate_t1.cityId = ''
        this.formValidate_t1.cityName = ''
      }
    },
    // 上级公司选择
    superCompanyIdChange (val) {
      if (val) {
        this.formValidate_t1.superCompanyName = val.label
      }
    },
    // 客户分类选择
    categoryChange (val) {
      if (val) {
        this.formValidate_t1.categoryName = val.label
      }
    },

    // 第一步保存--基本信息
    stepSubmit_1 (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          dataApi.postCustomer(this.formValidate_t1).then((res) => {
            if (res.data.success) {
              this.$Message.success(res.data.message)
              this.createCustomerId = res.data.data.id
              this.hasCustomerId = true
              this.createCurrent++
            } else {
              
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
        } else {
          this.$Message.error('有必填项未填！')
        }
      })
    },
    stepSubmit_2 () {
      if (this.logo_img) {
        this.$refs.licenseUploadRef.post(this.logo_img)
      }
      this.createModal = false
      this.createCurrent = 0
      this.$refs['formValidate_t1'].resetFields()
      this.$emit('get-list')
    },

    // logo执照
    licenseUpload (file) {
      this.logo_img = file
      console.log(file)
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        const _base64 = reader.result
        this.imgUrl = _base64
      }
      return false
    },
    deleteImg () {
      this.logo_img = ''
      this.imgUrl = ''
    },
    previewImg () {
      this.$emit('preview', this.imgUrl)
    },

    getEnum () {
      let groupNames = 'customer.type,customer.status'
      dataApi.getEnum({
        groupName: groupNames
      }).then((res) => {
        console.log(res)
        this.cooperateType_arr = this.getItems(res.data, 'customer.type')
        this.cooperateStatuseType_arr = this.getItems(res.data, 'customer.status')
      })
    },
    getItems (arr, key) {
      let object = arr.find((item) => {
        return item.group === key
      })
      return object.items
    }
  }
}
</script>
<style lang="less">
  .lzw-style{
    &.ivu-select-disabled .ivu-select-selection{
      color: #333;
    }
  }
</style>
<style lang="less" scoped>
  .und-line{
    text-decoration: underline;
    cursor: pointer;
    &:hover{
      color: #2d8cf0;
    }
  }
  .d-flex{
    display: flex;
    align-items: center;
  }
  .position-relative{
    .license-img{
      width: 100%;
      height: 100%;
      cursor: pointer;
      line-height: 80px;
      text-align: center;
    }
    img{
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .img-close{
      position: absolute;
      top: -8px;
      right: -8px;
      z-index: 9;
      cursor: pointer;
    }
  }
  .my-tag {
    display: inline-block;
    padding: 5px 30px 5px 10px;
    border-radius: 4px;
    position: relative;
    border: 1px solid #dcdee2;
    overflow: hidden;
    &:hover{
      color: @main_color;
      cursor: pointer;
      // border-color: @main_color;
    }
    &:after{
      content: '';
      width: 1px;
      height:100%;
      background-color: #dcdee2;
      position: absolute;
      top: 0;
      right: 20px;
    }
    .img-close{
      display: inline-block;
      width: 20px;
      height: 100%;
      position: absolute;
      line-height: 30px;
      top: 0;
      right: 0;
      font-size: 20px;
      &:hover{
        background-color: @main_color;
        color: #fff;
        // cursor: pointer;
      }
    }
  }
</style>
